package com.yc.demo.d0730;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter( urlPatterns = {"/page/cart.html",
        "/page/myinfo.html","/page/myorder.html",
        "/user/test/a.html"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        final HttpSession session = req.getSession();
        if(session.getAttribute("loginedUser") == null){
            // 获取当前请求地址
            final String requestURI = req.getRequestURI();
            // 保存到会话中
            session.setAttribute("requestURI", requestURI);

            // 获取上下文路径 web_demo_war_exploded
            final String contextPath = req.getContextPath();
            // 未登录 => 跳转登录页 =>
            resp.sendRedirect(contextPath + "/login.html?code=1"); // 404
            // 必须 return
            return;
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
